//
//  UserEntity.m
//  HLX
//
//  Created by john on 9/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UserEntity.h"
#import "Glob.h"
@implementation UserEntity
@synthesize uid = _uid, encryptkeys = _encryptkeys, phone = _phone, usertype = _usertype, email = _email, password = _password, zname=_zname,signature=_signature;

+ (id)createWithDictionary:(NSDictionary*)dictionary andPassword:(NSString*)pass
{
    if (dictionary && dictionary.count > 3) {
		UserEntity* entity = [UserEntity new];
		entity.uid = [dictionary objectForKey:@"userid"];
        entity.encryptkeys = [dictionary objectForKey:@"encryptkeys"];
		entity.name = [dictionary objectForKey:@"username"];
		entity.usertype = [dictionary objectForKey:@"usertype"];
        entity.phone = [dictionary objectForKey:@"phone"];
        entity.password = pass;
        entity.zname=[dictionary objectForKey:@"nickname"];
        entity.pic=[NSString stringWithFormat:@"%@%@",IMAGEPATH,[dictionary objectForKey:@"pic"]];
        entity.email=[dictionary objectForKey:@"email"];
        entity.signature=[dictionary objectForKey:@"signature"];
        entity.integral = [dictionary objectForKey:@"integral"];
        if ([entity.integral isEqualToString:@""]) {
            entity.integral = @"0";
        }
		entity.level = [dictionary objectForKey:@"level"];
        if ([entity.level isEqualToString:@""]) {
            entity.level = @"1";
        }
        entity.beans = [dictionary objectForKey:@"beans"];
        if ([entity.beans isEqualToString:@""]) {
            entity.beans = @"0";
        }
        return entity;
	}
	else {
		return nil;
	}
}

+ (NSArray*)findAllUserAccounts
{
	return [UserEntity allObjects];
}

+ (UserEntity*)findUserAccountByName:(NSString*)username
{
	return (UserEntity*)[UserEntity findFirstByCriteria:[NSString stringWithFormat:@"WHERE name = '%@'", username]];
}

- (NSString*)description
{
	return [NSString stringWithFormat:@"uid: %@, name: %@", self.uid, self.name];
}

- (void)saveUserAccount
{
	UserEntity* entity = [UserEntity findUserAccountByName:self.name];
	if (entity) {
		if (self.password.length > 0 && ![self.password isEqualToString:entity.password]) {
			entity.password = self.password;
        }
        [entity save];
	}
	else {
        
		[self save];
	}
}

@end
